var poilabel=[];
var XMLRequest=null;
var RequestInfo=null;
var vehicleTimer=null;
var geocoder=null;
/* Geofencing variable */
var latlngs=[];
var mypolygon=null;
var create_polygon=false;
var gf_marker=null;
var gf_label=null;	
/* End Geofencing variable */

var markers=[];
var map=null;
var labels=[];
var infowindow= null;
var polyline= null;
var paths	=[];
var vh_selected="";

var _0x7ae8=["\x68\x74\x74\x70\x3A\x2F\x2F\x6F\x73\x6D\x2E\x6E\x61\x76\x69\x67\x61\x73\x69\x2E\x6E\x65\x74\x2F\x6E\x61\x76\x6E\x65\x74\x2D\x68\x79\x62\x72\x69\x64\x2F","\x2F","\x78","\x79","\x2E\x70\x6E\x67","\x6D\x61\x70\x73","\x50\x65\x74\x61\x20\x4C\x6F\x6B\x61\x6C\x20\x49\x6E\x64\x6F\x6E\x65\x73\x69\x61\x20\x28\x55\x70\x74\x6F\x64\x61\x74\x65\x29","\x4C\x6F\x63\x61\x6C"];var localMapType={getTileUrl:function (_0xe1c6x2,_0xe1c6x3){return _0x7ae8[0]+_0xe1c6x3+_0x7ae8[1]+_0xe1c6x2[_0x7ae8[2]]+_0x7ae8[1]+_0xe1c6x2[_0x7ae8[3]]+_0x7ae8[4];} ,tileSize: new google[_0x7ae8[5]].Size(256,256),isPng:true,maxZoom:18,minZoom:0,alt:_0x7ae8[6],name:_0x7ae8[7]};
var _0xd028=["\x6D\x61\x70\x73"];var localMap= new google[_0xd028[0]].ImageMapType(localMapType);
initmap = function() 
{
   	maxZ = 18;
   	minZ = 1;
	bounded=false;
	geocoder = new google.maps.Geocoder();
	var latlng = new google.maps.LatLng(-0.789275,113.921327);
   	var myOptions = {
   		zoom: 5,
   		center: latlng,
   		mapTypeId: google.maps.MapTypeId.ROADMAP,/*Local*/
	    mapTypeControlOptions: {
	      mapTypeIds: [google.maps.MapTypeId.ROADMAP, 
	      				google.maps.MapTypeId.HYBRID, 
	      				google.maps.MapTypeId.TERRAIN,'Local']
	    }	
   	};
	
	map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
	map.mapTypes.set('Local', localMap);
	
	google.maps.event.addListener(map,"maptypeid_changed",function(){
		map.mapTypes[map.getMapTypeId()].maxZoom = maxZ;	
		map.mapTypes[map.getMapTypeId()].minZoom = minZ;
		google.maps.event.trigger(map, "zoom_changed");
	});	
}

GF_init=function()
{
	latlngs=[];
	var polyOptions = {
		path: latlng,
		strokeColor: "#FF0000",
		strokeOpacity: 0.8,
		strokeWeight: 2,
		fillColor: "#0000FF",
		fillOpacity: 0.6
	}
	mypolygon = new google.maps.Polygon(polyOptions);
	mypolygon.setMap(map);
	create_polygon=true;	
}
update_polygon=function(point){
	if( create_polygon==true)
	{
		latlng=mypolygon.getPath();
		latlng.push(point.latLng);		
	}
}
polygon_clear=function(){
	if( create_polygon==true)
	{
		mypolygon.setMap(null);
		mypolygon=null;
		
		$('#gf_set').show();
		$('#gf_cancel').hide();
		$('#gf_save').hide();
		create_polygon=false;
	}
}
polygon_save=function(){
	
		if(latlng){
			alert(latlng);
		}
}

map_resize = function()
{
	google.maps.event.trigger(map, 'resize');
}
show_hide_poi=function(){
	var zoomLevel =  map.getZoom();
	if( poilabel==null) return;
	if(  poilabel.length>0)
	{
		if( zoomLevel >= 10 )
		{
			if(poilabel){
				for(i in poilabel){
					poilabel[i].setMap(map);	
				}	
				//labels = [];
			}
		}else{
			if(poilabel){
				for(i in poilabel){
					poilabel[i].setMap(null);	
				}	
				//labels = [];
			}
		}

	}
}
poi_refresh = function()
{
	//alert('Load POI');
	$.ajax({
		type:'GET',
		dataType:'xml',
		url:'required_php/xml_poi.php',
		success:function(xml)
		{
		//alert(xml);
			$(xml).find('track').each(function()
			{
				var id 			= $(this).attr('id');
				var nama 		= $(this).attr('nama');
				var ket 		= $(this).attr('ket');
				var lat 		= $(this).attr('lat');
				var lng 		= $(this).attr('lng');
				var latlng 		= new google.maps.LatLng(parseFloat(lat),parseFloat(lng));
				//alert(lat+":"+lng);
				 var marker = new google.maps.Marker({
					position	:latlng, 
					title		:nama +'-'+ ket		
				 });	    
				var label = map_label(nama,marker);
				//pois.push(marker);
				poilabel.push(label);				
			});
		}	
	});
	
}
vehicle_reload = function(clear,bound)
{
	if( vehicleTimer !='') clearTimeout(vehicleTimer);
	if( XMLRequest !=null) XMLRequest.abort();	
	
	if( clear ==true){
		clear_vehicle_marker();
	}
	 XMLRequest=$.getJSON('required_php/json_gps.php',function(data){
		 if(data.length>0)
		 {
			 $.each(data,function(i,item){
				var vld=true;						
				var id = item['id'];
				var lat = parseFloat(item['lat']);
				var lng = parseFloat(item['lng']);
				var spd = parseFloat(item['spd']);
				var agl = parseFloat(item['agl']);
				if( (lat==NaN) || (lng==NaN)) vld=false;
				if( (lat=='NaN') || (lng=='NaN')) vld=false;
				if( (lng=='0') || (lng==0)) vld=false;
				if( vld == true )
				{
					var latlng = new google.maps.LatLng(lat,lng);				
					var marker = map_marker(id,'marker_1',latlng,agl,spd,0);
							var lbl = map_label(id,item['plat'],marker);							
							labels.push(lbl);
                                                        markers.push(marker);
					if( vh_selected == id ){
						map.setCenter(latlng);								
						if(infowindow) infowindow.setPosition(latlng);							
					}			
				}
			});
			 if( bound ==true){
					var bounds = new google.maps.LatLngBounds();
					if(markers){
						for(i in markers){
							bounds.extend(markers[i].getPosition());
						}
						map.fitBounds(bounds);	
					}
					if( markers.length<=0){
						var latlng = new google.maps.LatLng(-0.789275,113.921327);
						map.setCenter(latlng);
						map.setZoom(5);
					}
				}
		 }
	 });
	vehicleTimer=setTimeout("vehicle_reload(true,false);",30000);	
}
update_marker = function(datagps){
	
	if( reqProcess !=null) reqProcess.abort();	
	reqProcess=$.ajax({
		type:'GET',
		data: { vhArray : datagps },
		url:'required_php/xml_session_vh.php',
		success:function(result)
		{
			if( result=='OK'){
				vehicle_reload(true,true);
			}
		}	
	});	
}
getVehicle=function(id){
	var loc=-1;
	if(markers){
		for(i in markers){
			if( markers[i].getTitle()==id){
				loc=i;
				break;
			}
		}
	}
	if( loc !=-1){
		return markers[loc];
	}else{ return null;}
}

marker_zoom=function(id){
	if(markers){
		for(i in markers){
			if( markers[i].getTitle()==id){
				markers[i].setMap(map);		
				map.setCenter(markers[i].getPosition());
				if( map.getZoom()<14) map.setZoom(14);
				google.maps.event.trigger(markers[i], 'click');
				break;
			}
		}
	}
}
reverseGeocoding=function(id,marker) {
  var address="";
  //,marker.getPosition().lng()
  var lat = parseFloat(marker.getPosition().lat());
  var lng = parseFloat(marker.getPosition().lng());
  var latlng = new google.maps.LatLng(lat, lng);
  //Tampilkan Info Window animasi
  if(infowindow) infowindow.close();			
	infowindow = new google.maps.InfoWindow({content: "<div class='infowindow'><img  height='16' width='142' src='required_img/loader.gif'><div>Get Last Vehicle Info.... Wait..</div></div>"});
	infowindow.open(map, marker);	
  geocoder.geocode({'latLng': latlng}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      if (results[1]) {
        address=results[1].formatted_address;
      } else {
        address='No results found';
      }
    } else {
      address='Geocoder failed due to: ' + status;
    }
	infowindow.setContent(address);
	RequestInfo=$.ajax({
	  url: 'required_php/vh_getinfo.php?id='+id+'&addr='+ address,
	  success: function(data){		
			infowindow.setContent(data);	
	  }
	});
  });
 
  
  
}
  
getInfoWindow=function(id,marker){    
	//if( RequestInfo !=null) RequestInfo.abort();
	var address=reverseGeocoding(marker.getPosition().lat(),marker.getPosition().lng());
	if(infowindow) infowindow.close();			
		infowindow = new google.maps.InfoWindow({content: "<div class='infowindow'><img  height='16' width='142' src='required_img/loader.gif'><div>Get Last Vehicle Info.... Wait..</div></div>"});
		infowindow.setContent(address);
		infowindow.open(map, marker);	
		
	/*RequestInfo=$.ajax({
	  url: 'required_php/vh_getinfo.php?id='+id,
	  success: function(data){		
		infowindow.setContent(address);
		//infowindow.setContent(data);
	  }
	});*/
}
map_marker = function(id,m_type,latlng,angle,speed,trail)
{
	var marker = new google.maps.Marker({
		title:id,
		position:latlng, 
		map: map,
		icon:marker_icon(m_type,angle,speed,trail)		
	});
	google.maps.event.addListener(marker,"click",function(){
		vh_selected=id;
		//getInfoWindow(id,marker);		
		reverseGeocoding(id,marker);
	});		
	return marker;
}
map_label = function(id,vehicle,marker)
{
	var label = new Label({
		map: map,
		id:	id
	});
	label.bindTo('position',marker,'position');
	label.set('text',vehicle);
	return label;	
}
remove_marker=function(id){
	if(labels){
		for(i in labels){
			if( labels[i].id==id){
				labels[i].setMap(null);	
				labels.splice(i,1);
			}
		}	
	}
	if(markers){
		for(i in markers){
			if( markers[i].getTitle()==id){
				markers[i].setMap(null);
				markers.splice(i,1);
			}
		}		
	}
}
clear_vehicle_marker = function()
{
	var i;
	paths = [];
	if(polyline) polyline.setMap(null);	
	if(markers){
		for(i in markers) markers[i].setMap(null);		
		markers = [];
	}
	if(labels){
		for(i in labels)labels[i].setMap(null);		
		labels = [];
	}
}

map_polyline = function(){
	polyline = new google.maps.Polyline({
				path: paths,
				strokeColor: "#9797ff",
				strokeOpacity: 0.7,
				strokeWeight: 5	
			});
	polyline.setMap(map);
}
map_marker_image = function(url,wi,he,aw,ah){
	var mi = new google.maps.MarkerImage(
		url,
		new google.maps.Size(wi,he),
		new google.maps.Point(0,0),
		new google.maps.Point(aw,ah)
	);
	return mi;
}
marker_icon = function(m,a,s,t)
{
	var d='',icon='';
	if( (a>337.5 || a<=22.5) || a==0) d = 'U';
	if(a>22.5 && a<=67.5) d = 'UR';
	if(a>67.5 && a<=112.5) d = 'R';
	if(a>112.5 && a<=157.5) d = 'DR';
	if(a>157.5 && a<=202.5) d = 'D';
	if(a>202.5 && a<=247.5) d = 'DL';
	if(a>247.5 && a<=292.5) d = 'L';
	if(a>292.5 && a<=337.5) d = 'UL';
	
	if(m=='marker_1'){
		if(d=='U') {
			if(s==0) {
				if(t==0) icon=map_marker_image('required_img/marker_1/red-0.gif',32,37,20,33);  
				else icon=map_marker_image('required_img/marker_1/blue_dot.png',21,23,0,0); 
			}else {
				if(t==0) icon=map_marker_image('required_img/marker_1/blue-0.gif',32,37,20,33);  
				else icon=map_marker_image('required_img/marker_1/blue_dot_run.png',42,43,20,33); 
			}
		}
		if(d=='UR') {
			if(s==0) {
				if(t==0) icon=map_marker_image('required_img/marker_1/red-45.gif',32,37,20,33);  
				else icon=map_marker_image('required_img/marker_1/blue_dot.png',21,23,0,0); 
			}else {
				if(t==0) icon=map_marker_image('required_img/marker_1/blue-45.gif',32,37,20,33);  
				else icon=map_marker_image('required_img/marker_1/blue_dot_run.png',42,43,20,33); 
			}
		}
		if(d=='R') {
			if(s==0) {
				if(t==0) icon=map_marker_image('required_img/marker_1/red-90.gif',42,37,20,33);  
				else icon=map_marker_image('required_img/marker_1/blue_dot.png',21,23,0,0); 
			}else {
				if(t==0) icon=map_marker_image('required_img/marker_1/blue-90.gif',42,37,20,33);  
				else icon=map_marker_image('required_img/marker_1/blue_dot_run.png',42,43,20,33); 
			}
		}
		if(d=='DR') {
			if(s==0) {
				if(t==0) icon=map_marker_image('required_img/marker_1/red-135.gif',32,37,20,33);  
				else icon=map_marker_image('required_img/marker_1/blue_dot.png',21,23,0,0); 
			}else {
				if(t==0) icon=map_marker_image('required_img/marker_1/blue-135.gif',32,37,20,33);  
				else icon=map_marker_image('required_img/marker_1/blue_dot_run.png',42,43,20,33); 
			}
		}
		if(d=='D') {
			if(s==0) {
				if(t==0) icon=map_marker_image('required_img/marker_1/red-180.gif',32,37,20,33);  
				else icon=map_marker_image('required_img/marker_1/blue_dot.png',21,23,0,0); 
			}else {
				if(t==0) icon=map_marker_image('required_img/marker_1/blue-180.gif',32,37,20,33);  
				else icon=map_marker_image('required_img/marker_1/blue_dot_run.png',42,43,20,33); 
			}
		}
		if(d=='DL') {
			if(s==0) {
				if(t==0) icon=map_marker_image('required_img/marker_1/red-225.gif',32,37,20,33);  
				else icon=map_marker_image('required_img/marker_1/blue_dot.png',21,23,0,0); 
			}else {
				if(t==0) icon=map_marker_image('required_img/marker_1/blue-225.gif',32,37,20,33);  
				else icon=map_marker_image('required_img/marker_1/blue_dot_run.png',42,43,20,33); 
			}
		}
		if(d=='L') {
			if(s==0) {
				if(t==0) icon=map_marker_image('required_img/marker_1/red-270.gif',32,37,20,33);  
				else icon=map_marker_image('required_img/marker_1/blue_dot.png',21,23,0,0); 
			}else {
				if(t==0) icon=map_marker_image( 'required_img/marker_1/blue-270.gif',42,37,20,33);  
				else icon=map_marker_image('required_img/marker_1/blue_dot_run.png',42,43,20,33); 
			}
		}
		if(d=='UL') {
			if(s==0) {
				if(t==0) icon=map_marker_image('required_img/marker_1/red-315.gif',32,37,20,33);  
				else icon=map_marker_image('required_img/marker_1/blue_dot.png',21,23,0,0); 
			}else {
				if(t==0) icon=map_marker_image('required_img/marker_1/blue-315.gif',32,37,20,33);  
				else icon=map_marker_image('required_img/marker_1/blue_dot_run.png',42,43,20,33); 
			}
		}
	}
	return icon;
}